<template>
  <el-dialog
    title="分配权限"
    :visible="assignDialogVisible"
    width="50%"
    @close="closeDialog"
    @open="openDialog">
    <!-- data：指定 el-tree 渲染的树形结构数据 -->
    <!-- props：可以修改 el-tree 默认读取的字段 -->
    <!-- default-expand-all：默认展开所有节点 -->
    <!-- show-checkbox：给每个树形节点前面添加选择框 -->
    <!-- check-strictly：取消父子节点的关联 -->
    <!-- node-key：给树形结构中的每个节点都绑定一个 key 值 -->
    <el-tree
      ref="treeRef"
      :data="list" 
      :props="defaultProps"
      default-expand-all
      show-checkbox
      check-strictly
      node-key="id">
    </el-tree>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('close-dialog')">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { assignPermission, getRoleDetail } from '@/api/setting'
import { transTree } from '@/utils/transTree'

export default {
  props: {
    assignDialogVisible: {
      type: Boolean,
      required: true
    },
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [],
      defaultProps: {
        label: 'name'
      }
    }
  },
  methods: {
    // 关闭弹窗
    closeDialog() {
      this.$emit('close-dialog')
    },
    // 打开弹窗时的回调函数
    async openDialog() {
      // 获取权限点列表数据
      const res = await getPermissionList()
      this.list = transTree(res.data)
      const roleDetail = await getRoleDetail(this.roleId)
      // setCheckedKeys 方法的作用：给 el-tree 设置选中节点
      this.$refs.treeRef.setCheckedKeys(roleDetail.data.permIds)
    },
    // 给角色分配权限
    async submit() {
      // getCheckedKeys 方法的作用：获取到选中的节点的 key 值所组成的数组
      await assignPermission({
        id: this.roleId,
        permIds: this.$refs.treeRef.getCheckedKeys()
      })
      // 提示用户
      this.$message.success('分配权限成功')
      // 关闭弹窗
      this.$emit('close-dialog')
    }
  }
}
</script>

<style>

</style>